package clues.bihu.cluesaccident

import android.annotation.TargetApi
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Context.NOTIFICATION_SERVICE
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.support.v4.app.NotificationCompat
import android.text.TextUtils
import android.widget.Toast
import cn.jpush.android.api.JPushInterface
import com.orhanobut.logger.Logger
import org.json.JSONException
import org.json.JSONObject


class MyReceiver : BroadcastReceiver() {
    private val TAG = "JIGUANG-Example"
    private var mIntent: Intent? = null
    private var notifactionId: Int = 0
    private var mClueid = 0
    private var messageType = 0
    private var mContext: Context? = null
    override fun onReceive(context: Context?, intent: Intent?) {
        mContext = context
        val bundle = intent?.extras
        Logger.d(TAG, "[BihuReceiver] onReceive - " + intent?.getAction() + ", extras: " + printBundle(bundle!!))
        when (intent?.action) {
            JPushInterface.ACTION_REGISTRATION_ID -> {
                val regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID)
                Logger.d(TAG, "[BihuReceiver] 接收Registration Id : " + regId!!)
                Preference.saveString("REGISTRATION_ID", regId)
            }
            JPushInterface.ACTION_MESSAGE_RECEIVED -> {
                Logger.d(TAG, "[BihuReceiverl] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE)!!)
//                processCustomMessage(context!!, bundle)
            }
            JPushInterface.ACTION_NOTIFICATION_RECEIVED -> {
                if (Preference.catchString("flutter." + Preference.TOKEN, "") == "") {
                    return
                }
                Logger.d(TAG, "[BihuReceiver] 接收到推送下来的通知")
                notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID)
                Logger.d(TAG, "[BihuReceiver] 接收到推送下来的通知的ID: $notifactionId")
                val title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE)
                if (title == "出险通知") {
//                    NotifyMusicPlayUtil.playNotifyMusic(NotifyMusicPlayUtil.initMeidaPlayer(context!!, R.raw.car_accident_new))
                }
                processCustomMessage(context!!, bundle)
            }
            JPushInterface.ACTION_NOTIFICATION_OPENED -> {
                Logger.e("dsfjlsdkfjldsjfdsjfdsfjldjsfjdlsfjdslk")
                Toast.makeText(context, "用户点击打开了通知", Toast.LENGTH_LONG).show()
//                messageSkip(mContext!!, bundle)

            }
            JPushInterface.ACTION_RICHPUSH_CALLBACK -> {
                Logger.d(TAG, "[BihuReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA)!!)
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..
            }
            JPushInterface.ACTION_CONNECTION_CHANGE -> {
                val connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false)
                Logger.w(TAG, "[BihuReceiver]" + intent.action + " connected state change to " + connected)
            }
            else -> {
                Logger.d(TAG, "[BihuReceiver] Unhandled intent - " + intent?.getAction()!!)
            }
        }
    }

    /**
     * 消息跳转
     */
    private fun messageSkip(mContext: Context, bundle: Bundle) {

        val agentId = Preference.catchInt(Preference.AGENTID, 0)
        if (agentId != 0) {
            //暂时没有返回线索id,到时候只需要放开
            val Params = bundle.getString(JPushInterface.EXTRA_EXTRA)
            val mObject = JSONObject(Params)
            mClueid = mObject.getInt("ClueId")
            val i = Intent(mContext, HomeActivity::class.java)
            i.putExtras(bundle)
            i.putExtra("tag", "jpush")
            i.putExtra("clueid", mClueid)
            //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
            mContext.startActivity(i)
//            RxBus.getDefault().post(NotifyRefreshClueData(-1))
        } else {
//            val i = Intent(mContext, LoginActivity::class.java)
//            i.putExtras(bundle)
//            //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            i.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
//            mContext.startActivity(i)
        }

    }


    // 打印所有的 intent extra 数据
    private fun printBundle(bundle: Bundle): String {
        val sb = StringBuilder()
        for (key in bundle.keySet()) {
            if (key == JPushInterface.EXTRA_NOTIFICATION_ID) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key))
            } else if (key == JPushInterface.EXTRA_CONNECTION_CHANGE) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key))
            } else if (key == JPushInterface.EXTRA_EXTRA) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Logger.i(TAG, "This message has no Extra data")
                    continue
                }
                try {
                    val json = JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA))
                    val it = json.keys()

                    while (it.hasNext()) {
                        val myKey = it.next()
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]")
                    }
                } catch (e: JSONException) {
                    Logger.e(TAG, "Get message extra JSON error!")
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key))
            }
        }
        return sb.toString()
    }

    private fun processCustomMessage(context: Context, bundle: Bundle) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = "message"
            val channelName = "推修通知"
            val importance = NotificationManager.IMPORTANCE_HIGH
            createNotificationChannel(context, channelId, channelName, importance)
        }
        val notificationManager = context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = notificationManager.getNotificationChannel("message")
            if (channel.importance == NotificationManager.IMPORTANCE_NONE) {
                val intent = Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
                intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
                intent.putExtra(Settings.EXTRA_CHANNEL_ID, channel.id)
                context.startActivity(intent)
            }
        }

        val builder = NotificationCompat.Builder(context, "message")
        val title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE)  //推送标题
        val msg = bundle.getString(JPushInterface.EXTRA_ALERT)   //推送消息
        builder.setAutoCancel(true)
                .setContentText(msg)
                .setContentTitle(title)
                .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_logo))
                .setSmallIcon(R.drawable.notify_gray_head)
                .setDefaults(Notification.DEFAULT_SOUND)
//                .setSound(Uri.parse("android.resource://" + context.packageName + "/" + R.raw.test))
        val params = bundle.getString(JPushInterface.EXTRA_EXTRA)
        val mObject = JSONObject(params)
        mClueid = mObject.getInt("ClueId")
        messageType = mObject.getInt("MessageType")
        mIntent = Intent(context, IntentPlatformActivity::class.java)
        bundle.putString("ClueId", mClueid.toString())
        bundle.putInt("MessageType", messageType)
        mIntent?.putExtras(bundle)
        mIntent?.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
        val pendingIntent = PendingIntent.getActivity(context, 0, mIntent, PendingIntent.FLAG_CANCEL_CURRENT)
        builder.setContentIntent(pendingIntent)
        notificationManager.notify(notifactionId, builder.build())
    }

    @TargetApi(Build.VERSION_CODES.O)
    private fun createNotificationChannel(context: Context, channelId: String, channelName: String, importance: Int) {
        val channel = NotificationChannel(channelId, channelName, importance)
        val notificationManager = context.getSystemService(
                NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }
}